package api

import (
	"github.com/gin-gonic/gin"
	"server/internal/app/model"
	"server/internal/app/serv"
	"server/internal/database"
	"server/internal/pkg/response"
)

// DashboardApi Dashboard
var DashboardApi = new(dashboardApi)

type dashboardApi struct {
}

func (a dashboardApi) Index(c *gin.Context) {

	userInfo, _ := c.Get("userInfo")
	rules, _ := c.Get("rules")
	tissueName := a.GetTissueName(userInfo.(model.User).TissueId)

	Db := database.DB
	ids := serv.Tissue.GetTissueIds(userInfo.(model.User).TissueId, []int{})
	if rules.(string) != "*" {
		Db = Db.Where("tissue_id in ?", ids)

	}

	var userCount int64
	userDb := Db
	userDb.Table("user").Select("id").Count(&userCount)

	var enterpriseCount int64
	eDb := Db
	eDb.Table("enterprise").Select("id").Count(&enterpriseCount)

	data := make(map[string]any)
	data["tissue_name"] = tissueName
	data["user_count"] = userCount
	data["enterprise_count"] = enterpriseCount
	response.Success(c, data, "成功")
}

func (a dashboardApi) GetTissueName(id int) string {

	tissueName := ""
	Db := database.DB
	i := 0
	for {
		tissue := model.Tissue{}
		Db.Model(&tissue).Where("id=?", id).First(&tissue)
		if tissue.ID > 0 {
			if i == 0 {
				tissueName = tissue.Name
			} else {
				tissueName = tissue.Name + "-" + tissueName
			}

			id = tissue.Pid
			i++
		} else {
			break
		}

	}

	return tissueName
}
